package com.example.captcha.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.example.captcha.model.CaptchaConfiguration;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: hp
 * Date: 2025-01-14
 * Time: 16:10
 */
@RestController
@RequestMapping("/captcha")
public class CaptchaController {
    private static Logger logger = LoggerFactory.getLogger(CaptchaController.class);
    @Autowired
    private CaptchaConfiguration cp;
    //一分钟
    private static long VALID_TIME_OUT = 60 * 1000;
    @RequestMapping("/getCaptcha")
    public void getCaptcha(HttpServletResponse response,HttpSession session)  {
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(cp.getWidth(), cp.getHeight());
        session.setAttribute(cp.getSession().getKey(),lineCaptcha.getCode());
        session.setAttribute(cp.getSession().getDate(),new Date());
        System.out.println("System.out:验证码: " +lineCaptcha.getCode());
        logger.info("logger.info:验证码: " +lineCaptcha.getCode());
        try {
            lineCaptcha.write(response.getOutputStream());
            response.setHeader("Pragma", "No-cache");
            response.setContentType("image/jpeg");
            response.setCharacterEncoding("utf-8");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @RequestMapping("/check")
    public boolean check(String captcha,HttpSession session) {
        System.out.println("用户输入验证码: " + captcha);
        if(!StringUtils.hasLength(captcha)) {
            return false;
        }

        String code = (String) session.getAttribute(cp.getSession().getKey());
        Date date = (Date) session.getAttribute(cp.getSession().getDate());
        if(date == null || (System.currentTimeMillis() - date.getTime() > VALID_TIME_OUT)) {
            return false;
        }
        //不区分大小写
        return captcha.equalsIgnoreCase(code);
    }
}
